<style lang="scss" scoped>
  .mySplit {
    height: auto;
    display: flex;
    min-height: 400px;
  }

  .otherSplit {
    padding: 10px;
    overflow-y: auto;
    overflow-x: hidden
  }

  .split-pane {
    padding: 10px;
  }

  .ivu-checkbox-wrapper {
    font-size: 0px;
  }

  .myPosition {
    position: relative;
    left: 1%;
  }

  .my-columns {
    height: auto;
  }

  .clearfloat {
    clear: both;
    height: 0;
    font-size: 1px;
    line-height: 0px;
  }

  .mySplit > > > .ivu-tree-title {
    width: 100%;
    white-space: normal;
    padding-left: initial;
  }

  .myLeft {
    padding: 10px;
    border-right: 1px solid #dcdee2;
    width: 300px;
    padding-right: 20px;
  }

  .myRight {
    padding: 10px;
    width: 85%;
  }

  .ivu-table-wrapper-with-border {
    width: 100%;
  }
</style>
<template>
  <div>
    <Form
      v-if="!ifedit || dataInfo.spContent.datas.length > 0 || dataInfo.spContent.reqTeamLabel || dataInfo.spContent.fanTeamName"
      ref="teamInfo" :rules="validate" :model="applyinfo" :label-width="labelWidth" label-position="right"
      style="border: 1px solid #dcdee2;" class="form">
      <div style="padding: 10px;">
        <Row v-if="!ifedit">
          <Col span="8">
            <FormItem label="是否已有团队：">
              <RadioGroup v-model="dataInfo.spContent.hasAccount" @on-change="changeIsTeam">
                <Radio :label="0">无</Radio>
                <Radio :label="1">已拥有</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
        </Row>
        <Row v-if="dataInfo.spContent.hasAccount">
          <Col span="8">
            <FormItem label="所属团队：">
              <Input v-if="ifedit" v-bind:value="dataInfo.spContent.reqTeamLabel" :readonly="ifedit"/>
              <Select v-else v-model="dataInfo.spContent.reqTeamName" label-in-value @on-change="getApiServListByTeam">
                <Option v-for="(i,index) in teamList" :value="i.teamName" :key="index">{{i.label}}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <!-- 审批时需要填写的团队信息 -->
        <Row v-if=" dataInfo.spContent.fanTeamName">
          <Col span="8">
            <FormItem label="实际团队：">
              <Input v-bind:value="dataInfo.spContent.fanTeamLabel" :readonly="true"/>
            </FormItem>
          </Col>
        </Row>
        <Row v-if="!ifedit">
          <Col span="8">
            <FormItem label="是否申请API：">
              <RadioGroup v-model="isApplyAPI" @on-change="changeIsApplyAPI">
                <Radio :label="0">否</Radio>
                <Radio :label="1">是</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
        </Row>
        <template v-if="isApplyAPI == 1">
          <Row v-if="!ifedit">
            <Col span="8" style="padding-left: 10px;">
              <Button style="padding-left: 10px" type="primary" @click="showApiList">新增API接口</Button>
            </Col>
          </Row>
          <Row style="padding: 10px">
            <Table border :columns="apiServColumnsAll" :data="dataInfo.spContent.datas" width="100%">
              <template
               slot-scope=" { row, index }" slot="action">
              <Button type="primary" @click="getApiServInfo(row.apiCode)">详情</Button>
              <Button type="primary" v-if="!ifedit" @click="delApiServInfo(row.apiCode)">删除</Button>
        </template>
        </Table>
          </Row>
</template>
</div>
</Form>
<Modal v-model="showAPIServiceInfo" width="96%">
  <span slot="header" style="font-size: 22px; font-weight: bold;">{{apiTitle}}</span>
  <apiServiceInfo v-if="showAPIServiceInfo" :apiTitle="apiTitle" :apiServInfo="apiServInfo"></apiServiceInfo>
</Modal>
<Modal v-model="showApi" title="API申请" width="96%" :styles="{top: '5vh'}" @on-ok="onOk()">
  <div class="mySplit">
    <div class="myLeft" style="max-height: 75vh; overflow-y: auto;position: relative;font-size: 15px;">
      <Tree :data="treeData" :render="renderContent" @on-select-change="selectMenu"></Tree>
      <Spin size="large" fix v-if="loadingMyLeft"></Spin>
    </div>
    <div class="myRight" style="height: 75vh;overflow-y: auto;">
      <div v-if="!showApiInfo" style="position: relative;">
        <Input v-model="searchsApiName" placeholder="请输入API名称" style="width:auto;margin-left: 3%;"
               @on-enter="searchApi"/>
        <Button type="text" icon="md-refresh" @click="refreshTableData">刷新</Button>
        <Button type="primary" @click="searchApi">查询</Button>
        <div>
          <div v-for="(item, index) in apiServList" style="height: 132px; margin-top: 12px;">
            <div style="float: left;text-align:center;width: 3%;height: 132px;line-height: 132px;">
              <Checkbox v-model="apiServList[index].ifCheck" @on-change="checkApiServList(apiServList[index])"
                        v-if="item.state != 2 && item.state != 1">
                <span></span>
              </Checkbox>
              <span v-else>{{item.state == 2 ? '已申请':(item.state == 1 ? '申请中':'未申请')}}</span>
            </div>
            <div style="cursor: pointer;" @click="showAPIInfo(item.apiCode)">
              <Card style="width:97%; float: left;">
                <div style="height: 100px;">
                  <div style="text-align:center;float: left;">
                    <img src="../../../../../static/image/api.svg" height="100px;">
                  </div>
                  <div style="text-align:center;float: left;margin-left: 12px;">
                    <span style="font-size: 20px;font-weight: bold;">{{item.apiLabel}}</span>
                    <span style="margin-left: 12px;">
                          <span v-if="item.state == 2">
                            <Tag color="success">已申请</Tag>
                          </span>
                          <span v-else-if="item.state == 1">
                            <Tag color="primary">申请中</Tag>
                          </span>
                          <span v-else>
                            <Tag color="error">未申请</Tag>
                          </span>
                        </span>
                    <div style="text-align: left; font-size: 16px;bottom: 16px; position: absolute;">
                      <div style="float: left;">
                        <span>请求方式：<span style="color: #bbb; margin-right: 12px;">{{item.requestMethod}}</span></span>
                        <span>返回方式：<span style="color: #bbb; margin-right: 12px;">{{item.responseType}}</span></span>
                        <span>创建时间：<span style="color: #bbb; margin-right: 12px;">{{item.createDt}}</span></span>
                      </div>
                      <div style="float: left;">请求地址：<span
                        style="color: #bbb; margin-right: 12px;">{{item.requestUrl}}</span></div>
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          </div>
        </div>
        <div style="float: right;margin: 10px;">
          <Page :current="page" :total="total" :page-size="pageSize" show-total @on-change="changePage"></Page>
        </div>
        <Spin size="large" fix v-if="loadingInfo"></Spin>
      </div>
      <div v-else>
        <Button type="primary" @click="showApiInfo = false" style="margin-bottom: 12px;">返回</Button>
        <span style="font-size: 22px; font-weight: bold;margin-left: 12px;">{{apiServInfo.apiLabel}}</span>
        <div style="height: 65vh;overflow-y: auto;">
          <apiServiceInfo v-model="showAPIServiceInfo" :apiTitle="apiTitle" :apiServInfo="apiServInfo"></apiServiceInfo>
        </div>
      </div>
    </div>

  </div>
</Modal>
</div>
</template>

<script>
  import apiServiceInfo from './apiServiceInfo.vue'

  export default {
    name: "open_api_platform_model",
    components: {
      apiServiceInfo
    },
    data() {
      return {
        loadingInfo: false,
        showApiInfo: false, //选择api时查看详情
        searchsApiName: "",
        loadingMyLeft: false,
        loadingFanTeamName: false,
        showApi: false,
        pageSize: 5,
        page: 1,
        total: 0,
        showAPIServiceInfo: false, // 显示api详情model
        apiTitle: "", //api详情title
        title: "服务目录",
        validate: {},
        labelWidth: 140,
        checkApiServ: [], //勾选的api接口
        hasAccount: 0, //是否有团队
        isApplyAPI: 0, //是否申请API
        tableLoading: false,
        showTable: false,
        teamList: [], //团队集合
        apiServInfo: {
          "apiCode": "",
          "requestUrl": "",
          "apiLabel": "",
          "apiDescr": "",
          "requestMethod": "",
          "responseType": "",
          "createDt": "",
          "effDt": "",
          "expDt": "",
          "teamName": "",
          "archName": "",
          "publishDate": "",
          "requestParam": [{
            "name": "",
            "label": "",
            "required": "",
            "defaultVal": ""
          }],
          "responseBody": [{
            "name": "",
            "label": "",
            "fieldType": ""
          }]
        },
        apiServList: [], //api数据接口集合
        defaultApiServList: [], // 全部可选择的api
        applyinfo: {},
        apiServColumns: [{
          title: ' ',
          width: 90,
          align: 'center',
          slot: "select",
        },
          {
            title: 'API中文名',
            key: 'apiLabel',
            width: 200,
          },
          {
            title: '请求路径',
            key: 'requestUrl',
            width: 200,
          },
          {
            title: '描述',
            key: 'apiDescr',
            minWidth: 150
          },
          {
            title: '申请状态',
            key: 'state',
            width: 100,
            slot: "state",
          },
          // {
          //   title: "请求方法",
          //   key: "requestMethod",
          //   minWidth: 150
          // },
          // {
          //   title: "数据返回类型",
          //   key: "responseType",
          //   minWidth: 150
          // },
          // {
          //   title: "创建时间",
          //   key: "createDt",
          //   minWidth: 150
          // },
          // {
          //   title: "生效时间",
          //   key: "effDt",
          //   minWidth: 150
          // },
          {
            title: "操作",
            key: "action",
            slot: "action",
            width: 80,
            align: 'center',
          }
        ],
        apiServColumnsAll: [{
          title: 'API中文名',
          key: 'apiLabel',
          width: 200,
        },
          {
            title: '请求路径',
            key: 'requestUrl',
            width: 200,
          },
          {
            title: '描述',
            key: 'apiDescr',
            minWidth: 150
          },
          // {
          //   title: "请求方法",
          //   key: "requestMethod",
          //   minWidth: 150
          // },
          // {
          //   title: "数据返回类型",
          //   key: "responseType",
          //   minWidth: 150
          // },
          // {
          //   title: "创建时间",
          //   key: "createDt",
          //   minWidth: 150
          // },
          // {
          //   title: "生效时间",
          //   key: "effDt",
          //   minWidth: 150
          // },
          {
            title: "操作",
            key: "action",
            slot: "action",
            width: 150,
            align: 'center',
          }
        ],
        tableData: [],
        treeData: [],
        archName: "" //勾选的目录标识
      }
    },
    props: {
      isEdit: {},
      isEditTeam: {
        default: false
      },
      isHandel: {
        default: false
      },
      value: {},
      ifedit: {},
      projectId: {}
    },
    created: function () {
      console.log(" -------aaaaaa->", this.dataInfo.spContent)
      if (!this.dataInfo.spContent) {
        var spContent = {
          hasAccount: 0,
          reqTeamName: "",
          reqTeamLabel: "",
          fanTeamName: "",
          fanTeamLabel: "",
          datas: []
        }
        this.$set(this.dataInfo, "spContent", spContent)
      } else {
        if (this.dataInfo.spContent.datas.length > 0) {
          this.isApplyAPI = 1
          this.checkApiServ = this.dataInfo.spContent.datas
        }
        if (this.dataInfo.spContent.hasAccount == 1 || this.dataInfo.spContent.reqTeamLabel) {
          this.dataInfo.spContent.hasAccount = 1
          this.changeIsTeam(1)
        }
      }
    },
    mounted() {

    },

    methods: {
      /**
       *  显示api详情，在选择api时
       */
      showAPIInfo(apiCode) {
        this.loadingInfo = true
        var that = this
        var params = {
          apiCode: apiCode
        }
        // 调接口
        this.myAjax.get({
          url: this.CONFIG.progress_url + '/open-api-platform/getApiServInfo',
          that: that,
          params: params,
          success: function (data) {
            that.apiServInfo = data
            that.loadingInfo = false
            that.showApiInfo = true
          }
        })
      },
      /**
       * 加载全部
       */
      refreshTableData() {
        this.searchsApiName = ""
        this.getApiServList()
      },
      /**
       * 查找API
       */
      searchApi() {
        var temp = []
        this.defaultApiServList.forEach(item => {
          console.log("item = ", item)
          if (item.apiLabel.indexOf(this.searchsApiName) > -1) {
            temp.push(item)
          }
        })
        this.defaultApiServList = temp
        this.page = 1
        this.total = temp.length
        this.changePage(1)
      },
      seachAllTeamList(queryCond) {
        if (queryCond != "") {
          this.loadingFanTeamName = true
          this.utils.delay(() => {
            var that = this
            var params = {
              queryCond: queryCond
            }
            this.myAjax.get({
              url: this.CONFIG.progress_url + '/open-api-platform/getAllTeamList',
              that: that,
              params: params,
              success: function (data) {
                that.teamList = data
                that.$nextTick(() => {
                  that.loadingFanTeamName = false
                })
              }
            })
          }, 500)
        } else {
          this.teamList = []
        }
      },
      showApiList() {
        if (!this.treeData || this.treeData.length == 0) {
          this.getTreeData()
        }
        this.showApi = true
      },
      /**
       * 获取目录架构
       */
      getTreeData() {
        this.loadingMyLeft = true
        var that = this
        // that.treeData = that.handleCatalogInfo(data.data)
        // that.loadingMyLeft = false
        // that.getApiServList()

        this.myAjax.get({
          url: this.CONFIG.progress_url + '/open-api-platform/getCatalogInfo',
          that: that,
          success: function (data) {
            that.treeData = that.handleCatalogInfo(data)
            that.loadingMyLeft = false
            if (that.treeData.length > 0) {
              that.$set(that.treeData[0], "selected", true)
              that.archName = that.treeData[0].archName
            }
            that.getApiServList()
          }
        })
      },
      /**
       * 获取api目录
       */
      getApiServList() {
        this.loadingInfo = true
        this.showApiInfo = false
        var that = this
        var params = {
          user4AAccount: this.$store.state.user.fourA,
          teamName: this.dataInfo.spContent.reqTeamName,
          archName: this.archName
        }
//         var data = [
//             {
//                 "apiCode": "Test_Api_001",
//                 "requestUrl": "CM20200101",
//                 "apiLabel": "测试API001",
//                 "apiDescr": "测试API001描述",
//                 "requestMethod": "GET",
//                 "responseType": "json",
//                 "createDt": "2020-12-24 10:00:00",
//                 "state": "1",
//                 "effDt": "2020-12-24 10:00:00",
//                 "expDt": "2021-12-24 10:00:00",
//                 "teamName": "A001",
//                 "archName": "DIR_01",
//                 "publishDate": "2021-12-24 12:00:00"
//             },
//             {
//                 "apiCode": "Test_Api_002",
//                 "requestUrl": "CM20200102",
//                 "apiLabel": "测试API002",
//                 "apiDescr": "测试API002描述",
//                 "requestMethod": "GET",
//                 "responseType": "json",
//                 "createDt": "2020-12-24 10:00:00",
//                 "state": "0",
//         "effDt": "2020-12-24 10:00:00",
//         "expDt": "2021-12-24 10:00:00",
//         "teamName": "A001",
//         "archName": "DIR_01",
//         "publishDate": "2021-12-24 12:00:00"
//     },
//             {
//                 "apiCode": "Test_Api_002",
//                 "requestUrl": "CM20200102",
//                 "apiLabel": "测试API002",
//                 "apiDescr": "测试API002描述",
//                 "requestMethod": "GET",
//                 "responseType": "json",
//                 "createDt": "2020-12-24 10:00:00",
//                 "state": "2",
//         "effDt": "2020-12-24 10:00:00",
//         "expDt": "2021-12-24 10:00:00",
//         "teamName": "A001",
//         "archName": "DIR_01",
//         "publishDate": "2021-12-24 12:00:00"
//     }
// ]
//         that.page = 1
//         that.total = data.length
//         data.forEach(item => {
//           if (that.checkApiServ.findIndex(e => e.apiCode == item.apiCode) != -1) {
//             item.ifCheck = true
//           }
//         })
//         that.defaultApiServList = data

//         that.changePage(that.page)
//         that.tableLoading = false
        this.myAjax.get({
          url: this.CONFIG.progress_url + '/open-api-platform/getApiServListByTeam',
          that: that,
          params: params,
          success: function (data) {
            that.page = 1
            that.total = data.length
            data.forEach(item => {
              if (that.checkApiServ.findIndex(e => e.apiCode == item.apiCode) != -1) {
                item.ifCheck = true
              }
            })
            that.defaultApiServList = data

            that.changePage(that.page)
            that.loadingInfo = false
          }
        })
      },
      /**
       * 处理数据目录结构
       */
      handleCatalogInfo(data) {
        var temp = []
        if (data.length > 0) {
          data.forEach(item => {
            if (temp.length != 0) {
              var tempIndex = this.setChildren(temp, item)
              if (!tempIndex) {
                temp.push(item)
              }
            } else {
              temp.push(item)
            }
          })
        }
        console.log("tree = ", JSON.stringify(temp))
        return temp
      },
      /**
       * 设置其子目录
       */
      setChildren(treeData, item) {
        console.log("bianl = ", treeData)
        var treeTemp = JSON.parse(JSON.stringify(item))
        var tempIndex = false

        treeData.some(tree => {
          console.log("treeData = ", tree, treeTemp.parentId)
          if (tree.id === treeTemp.parentId) {
            tempIndex = true
            if (tree.children) {
              tree.children.push(treeTemp)
            } else {
              this.$set(tree, "children", [treeTemp])
            }
            return true
          } else {
            if (tree.children && tree.children.length > 0) {
              tempIndex = this.setChildren(tree.children, treeTemp)
            }
          }
        })
        return tempIndex
      },
      /**
       * 分页
       *
       * @param {Object} page
       */
      changePage(page) {
        var pageNumber = page * this.pageSize
        if (pageNumber > this.total) {
          this.apiServList = this.defaultApiServList.slice((page - 1) * this.pageSize, this.total)
        } else {
          this.apiServList = this.defaultApiServList.slice((page - 1) * this.pageSize, pageNumber)
        }
      },
      /**
       * 是否申请API
       */
      changeIsApplyAPI(value) {
        console.log("dataInfo--->", value)
        if (value == 0) {
          this.dataInfo.spContent.datas = []
        }
      },
      /**
       * 选择apiService
       * @param {Object} apiServ
       */
      checkApiServList(apiServ) {
        if (apiServ.ifCheck) {
          if (this.checkApiServ.findIndex(e => e.apiCode == apiServ.apiCode) == -1) {
            this.checkApiServ.push(apiServ)
          }
        } else {
          this.checkApiServ.splice(this.checkApiServ.findIndex(e => e.apiCode == apiServ.apiCode), 1)
        }

      },
      delApiServInfo(apiCode) {
        this.checkApiServ.splice(this.checkApiServ.findIndex(e => e.apiCode == apiCode), 1)
      },
      onOk() {
        this.dataInfo.spContent.datas = this.checkApiServ
        this.dataInfo.apiServTotal = this.total
      },
      /**
       * 根据团队标识获取数据接口
       * @param {Object} value
       */
      getApiServListByTeam(value) {
        console.log(" --------- 》 ", value)
        this.dataInfo.spContent.reqTeamName = value.value
        this.dataInfo.spContent.reqTeamLabel = value.label
        // this.$forceUpdate()
      },

      /**
       * 获取Api详情
       */
      getApiServInfo(apiCode) {
        this.showAPIServiceInfo = true
        var that = this
        var params = {
          apiCode: apiCode
        }
        // 调接口
        this.myAjax.get({
          url: this.CONFIG.progress_url + '/open-api-platform/getApiServInfo',
          that: that,
          params: params,
          success: function (data) {
            that.apiServInfo = data
            that.apiTitle = data.apiLabel
          }
        })
      },
      /**
       * 修改选项
       * @param {Object} value
       */
      changeIsTeam(value) {
        if (!this.ifedit) {
          console.log("this.ifedit = ", this.ifedit, value)
          if (value === 1 && this.teamList) {
            var that = this
            var params = {
              user4AAccount: this.$store.state.user.fourA,
              projectId: this.projectId
            }
            this.myAjax.get({
              url: this.CONFIG.progress_url + '/open-api-platform/getTeamListByUser',
              that: that,
              params: params,
              success: function (data) {
                that.teamList = data
              }
            })
          } else {
            this.dataInfo.spContent.reqTeamName = ""
            this.dataInfo.spContent.reqTeamLabel = ""
            this.dataInfo.spContent.datas = []
          }

        }
      },
      /**
       * 数据目录树形结构合
       */
      renderContent(h, {
        root,
        node,
        data
      }) {
        return h('span', {
          style: {
            fontSize: '18px'
          }
        }, [
          h('Icon', {
            props: {
              type: 'ios-folder-open'
            },
            style: {
              marginRight: '8px',
              color: "#5cadff",
            }
          }),
          h('span', data.label)
        ]);
      },
      /**
       * 选择api目录
       * @param {Object} menu
       */
      selectMenu(menu) {
        if (menu[0]) {
          console.log("selectMenu---->", menu[0])
          this.archName = menu[0].archName
          this.getApiServList()
        }
      }
    },
    computed: {
      dataInfo: {
        get: function () {
          return this.value;
        },

        set: function (value) {
          this.$emit('input', value);
        }
      }
    },
  }
</script>
